<template>
  <div class="order-detail-page">
    <!-- 顶部导航 -->
    <div class="nav-header">
      <button class="back-button" @click="goBack">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <path d="m15 18-6-6 6-6" />
        </svg>
      </button>
      <h2>订单详情</h2>
    </div>

    <!-- 加载中状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <div class="loading-text">加载中...</div>
    </div>

    <div v-else class="order-content">
      <!-- 订单状态 -->
      <div class="status-card">
        <div class="status-text">{{ getStatusText(orderInfo.status) }}</div>
        <div class="status-desc">{{ getStatusDescription(orderInfo.status) }}</div>
      </div>

      <!-- 收货地址 -->
      <div class="info-card">
        <div class="card-title">收货地址</div>
        <div class="address-info">
          <div class="contact">
            <span class="name">{{ orderInfo.recipientName }}</span>
            <span class="phone">{{ orderInfo.phone }}</span>
          </div>
          <div class="address">{{ orderInfo.address }}</div>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="info-card">
        <div class="card-title">商品信息</div>
        <div class="product-item">
          <img :src="orderInfo.productImageUrl" :alt="orderInfo.productName" class="product-image">
          <div class="product-info">
            <div class="product-name">{{ orderInfo.productName }}</div>
            <div class="product-price">
              <span class="price">¥{{ orderInfo.productPrice }}</span>
              <span class="quantity">x{{ orderInfo.quantity }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 订单信息 -->
      <div class="info-card">
        <div class="card-title">订单信息</div>
        <div class="order-info-list">
          <div class="info-item">
            <span class="label">订单编号</span>
            <span class="value">{{ orderInfo.orderNumber }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间</span>
            <span class="value">{{ formatDate(orderInfo.createTime) }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付方式</span>
            <!-- 假设支付方式是支付宝 -->
            <span class="value">支付宝</span>
          </div>
          <div v-if="orderInfo.payTime" class="info-item">
            <span class="label">支付时间</span>
            <span class="value">{{ formatDate(orderInfo.payTime) }}</span>
          </div>
        </div>
      </div>

      <!-- 价格信息 -->
      <div class="info-card">
        <div class="card-title">价格信息</div>
        <div class="price-info-list">
          <div class="price-item">
            <span>商品总价</span>
            <span>¥{{ orderInfo.productPrice * orderInfo.quantity }}</span>
          </div>
          <div class="price-item">
            <span>运费</span>
            <span>¥{{ orderInfo.shippingFee || 0 }}</span>
          </div>
          <div class="price-item total">
            <span>实付款</span>
            <span class="total-price">¥{{ orderInfo.totalPrice }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="bottom-actions" v-if="!loading">
      <button
        v-if="orderInfo.status === 'pending'"
        class="action-btn primary"
        @click="payOrder"
      >
        去支付
      </button>
      <button
        v-if="orderInfo.status === 'shipped' || orderInfo.status === 'paid'"
        class="action-btn primary"
        @click="confirmReceipt"
      >
        确认收货
      </button>
      <button
        v-if="orderInfo.status === 'completed'"
        class="action-btn primary"
        @click="reviewOrder"
      >
        评价
      </button>
      <button
        v-if="orderInfo.status === 'pending'"
        class="action-btn secondary"
        @click="cancelOrder"
      >
        取消订单
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const orderInfo = ref({})

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待付款',
    'paid': '待发货',
    'shipped': '待收货',
    'delivered': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 获取状态描述
const getStatusDescription = (status) => {
  const descMap = {
    'pending': '请尽快完成支付',
    'paid': '商家正在处理您的订单',
    'shipped': '商品正在配送中',
    'delivered': '交易已完成',
    'cancelled': '订单已取消'
  }
  return descMap[status] || ''
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 支付订单
const payOrder = () => {
  const orderInfo = {
    items: [{
      productId: orderInfo.value.productId,
      name: orderInfo.value.productName,
      price: orderInfo.value.productPrice,
      quantity: orderInfo.value.quantity,
      imageUrl: orderInfo.value.productImageUrl
    }],
    totalPrice: orderInfo.value.totalPrice,
    totalCount: orderInfo.value.quantity,
    discount: 0,
    ordersId: orderInfo.value.ordersId,
    orderNumber: orderInfo.value.orderNumber
  }

  router.push({
    path: '/order/payment',
    query: {
      orderInfo: JSON.stringify(orderInfo)
    }
  })
}

// 确认收货
const confirmReceipt = async () => {
  try {
    const confirmMessage = orderInfo.value.status === 'paid'
      ? '确认收到未发货商品可能会影响您的权益，确定要继续吗？'
      : '确认已收到商品？'

    if (confirm(confirmMessage)) {
      // 这里应该调用确认收货的API
      alert('确认收货成功！')
      orderInfo.value.status = 'completed'
    }
  } catch (error) {
    console.error('确认收货失败:', error)
    alert('确认收货失败，请稍后再试')
  }
}

// 评价订单
const reviewOrder = () => {
  router.push({
    path: `/order/review/${orderInfo.value.ordersId}`,
    query: { orderInfo: JSON.stringify(orderInfo.value) }
  })
}

// 取消订单
const cancelOrder = async () => {
  if (confirm('确定要取消订单吗？')) {
    try {
      // 这里应该调用取消订单的API
      alert('订单已取消')
      orderInfo.value.status = 'cancelled'
    } catch (error) {
      console.error('取消订单失败:', error)
      alert('取消订单失败，请稍后再试')
    }
  }
}

onMounted(() => {
  // 从路由参数中获取订单信息
  const orderInfoStr = route.query.orderInfo
  console.log('订单信息:', orderInfoStr)
  if (orderInfoStr) {
    try {
      orderInfo.value = JSON.parse(orderInfoStr)
    } catch (error) {
      console.error('解析订单信息失败:', error)
    }
  }
  loading.value = false
})
</script>

<style lang="scss" scoped>
.order-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 80px;
}

.nav-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 100;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

  .back-button {
    background: none;
    border: none;
    padding: 8px;
    margin-left: -8px;
    cursor: pointer;
  }

  h2 {
    flex: 1;
    text-align: center;
    margin: 0;
    font-size: 16px;
  }
}

.order-content {
  padding-top: 44px;
}

.status-card {
  background-color: #8B5CF6;
  color: white;
  padding: 20px 16px;

  .status-text {
    font-size: 18px;
    font-weight: 500;
    margin-bottom: 8px;
  }

  .status-desc {
    font-size: 14px;
    opacity: 0.9;
  }
}

.info-card {
  background-color: white;
  margin: 12px;
  border-radius: 8px;
  padding: 16px;

  .card-title {
    font-size: 15px;
    font-weight: 500;
    margin-bottom: 12px;
  }
}

.address-info {
  .contact {
    margin-bottom: 8px;

    .name {
      font-weight: 500;
      margin-right: 12px;
    }

    .phone {
      color: #666;
    }
  }

  .address {
    color: #333;
    line-height: 1.4;
  }
}

.product-item {
  display: flex;
  padding: 12px 0;

  .product-image {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 4px;
    margin-right: 12px;
  }

  .product-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .product-name {
      font-size: 14px;
      line-height: 1.4;
    }

    .product-price {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .price {
        color: #ff3b30;
        font-size: 15px;
      }

      .quantity {
        color: #999;
        font-size: 13px;
      }
    }
  }
}

.order-info-list, .price-info-list {
  .info-item, .price-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
    font-size: 14px;

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      color: #666;
    }

    &.total {
      margin-top: 8px;
      padding-top: 8px;
      border-top: 1px solid #f0f0f0;

      .total-price {
        color: #ff3b30;
        font-size: 16px;
        font-weight: 500;
      }
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px 16px;
  background-color: white;
  box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: flex-end;
  gap: 12px;

  .action-btn {
    padding: 8px 20px;
    border-radius: 20px;
    font-size: 14px;
    cursor: pointer;

    &.primary {
      background-color: #8B5CF6;
      color: white;
      border: none;
    }

    &.secondary {
      background-color: white;
      color: #666;
      border: 1px solid #ddd;
    }

    &:active {
      opacity: 0.9;
    }
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: white;

  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid rgba(139, 92, 246, 0.2);
    border-top-color: #8B5CF6;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 12px;
  }

  .loading-text {
    color: #666;
    font-size: 14px;
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}
</style>
